package com.common.frame.net

import com.common.frame.base.isDebug
import com.common.frame.net.log.LoggingInterceptor
import com.common.frame.utils.Utils
import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.util.concurrent.TimeUnit

object RetrofitHelper {

    private const val NET_CONNECTED_TIME_OUT: Long = 15
    private const val BASE_URL = "https://192.168.8.8/"
    private const val NET_READ_TIME_OUT: Long = 15
    private const val NET_WRITE_TIME_OUT: Long = 60
    private const val HTTP_CASH_FILE_DIR = "http_cash"
    private const val HTTP_CASH_SIZE = (1024 * 1024 * 10).toLong()

    val retrofit by lazy {
        Retrofit.Builder()
            .client(okHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL)
            .build()
    }


    fun okHttpClient(headerInterceptor: Interceptor? = null): OkHttpClient {
        val cacheDir = Utils.app.cacheDir.absolutePath + File.separator + HTTP_CASH_FILE_DIR
        val cacheFile = File(Utils.app.cacheDir, cacheDir)
        val builder = OkHttpClient.Builder()
        builder.connectTimeout(NET_CONNECTED_TIME_OUT, TimeUnit.SECONDS)
            .readTimeout(NET_READ_TIME_OUT, TimeUnit.SECONDS)
            .writeTimeout(NET_WRITE_TIME_OUT, TimeUnit.SECONDS)
            .cache(Cache(cacheFile, HTTP_CASH_SIZE))
//        HttpsUtil.getSslSocketFactory()?.let {
//            builder.sslSocketFactory(it.sSLSocketFactory, it.trustManager)
//        }
        headerInterceptor?.let {
            builder.addInterceptor(it)
        }
        if (isDebug) {
            builder.addInterceptor(LoggingInterceptor())
        }

        return builder.build()
    }

}